package com.Controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.entity.User;
import com.service.UserService;
import com.utils.VerifyCodeUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {
    private final static Logger log = LoggerFactory.getLogger(UserController.class);
@Autowired
   private UserService userService;

    @Autowired
   public UserController(UserService userService) {
        this.userService = userService;
   }

   //查询库内所有信息
   @RequestMapping("export")
   public void exportExcel(HttpServletResponse response) throws IOException {

        List<User> users1 = userService.lists();
        //生成excel
       log.info("导出当前数据库中的数据总数为：[{}]",users1.size());
      Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户列表信息","用户信息"),User.class,users1);
      response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("用户列表.xls","UTF-8"));
      ServletOutputStream outputStream = response.getOutputStream();

      workbook.write(outputStream);
      outputStream.close();
      workbook.close();

   }


    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/log";
    }

/*用户登录*/
    @RequestMapping("login")
    public String login(String username,String pwd,HttpSession session){
log.debug("本次登录用户名：{}",username);
log.debug("本次登录密码：{}",pwd);
//调用业务层
        try {
            User user = userService.login(username,pwd);
            //保存用户信息
            session.setAttribute("user",user);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/log";//登录失败回到登录页面
        }
//登录成功
 return "redirect:/index";
    }

   /* @RequestMapping("list")
    public String list(ModelMap map){

        List<User> list = userService.findAll();
        map.addAttribute("list",list);
        System.out.println("size="+list.size());
        return "list";
    }

    @RequestMapping("page")
    public String page(@RequestParam(required = false) int pageNum,
                       @RequestParam(required = false) int pageSize,
                       ModelMap map){
        List<User> list = userService.findAllByPage(pageNum,pageSize);
        map.addAttribute("list",list);
        System.out.println("size="+list.size());
        return "list";
    }
*/


    /*注册功能*/
@RequestMapping("register")
public String register(User user, String code, HttpSession session){
   log.debug("昵称：{},姓名{},密码：{},性别{},电话,{},",user.getUsername(),user.getRealname(),user.getPwd(),user.getGender(),user.getTelephone());
   log.debug("验证码信息：{}",code);
   //判断验证码正确
    try {
        String sessionCode = session.getAttribute("code").toString();
        if (!sessionCode.equalsIgnoreCase(code))throw new RuntimeException("验证码输入错误");
        //注册用户
        userService.register(user);
    } catch (RuntimeException e) {
        e.printStackTrace();
        return "redirect:/register";
    }
    return "redirect:/log";
}

//更新hr用户信息,
    @RequestMapping("update")
public String update(User user){

    log.debug("更新之后员工信息: id:{},姓名:{},真实姓名:{},性别:{},手机号:{},邮箱:{},入职日期:{}",
            user.getId(),user.getUsername(),user.getRealname(),user.getGender(),user.getTelephone(),user.getEmail(),user.getOnboarding());  //1.判断是否更新头像
    //4.没有更新头像直接更新基本信息
    userService.update(user);
    return "redirect:/user/findByPage";//更新成功,跳转到员工列表
}

    @RequestMapping("detail")
    public String detail(Integer id,Model model){
        log.debug("查询当前用户:{}",id);
        //查id
        User user = userService.findById(id);
        System.out.println(user);
        model.addAttribute("user",user);
        return "updateUser";
    }

    /*保存员工信息*/
    @RequestMapping("save")
    public String save(User user, MultipartFile img) throws IOException {
        log.debug("更新之后员工信息: id:{},姓名:{},真实姓名:{},性别:{},手机号:{},邮箱:{},入职日期:{}",
                user.getId(),user.getUsername(),user.getRealname(),user.getGender(),user.getTelephone(),user.getEmail(),user.getOnboarding());
        userService.save(user);
        return "redirect:/user/findByPage";
    }

    @RequestMapping("delete")
    public String delete(Integer id){
        log.debug("删除的员工id",id);
        userService.delete(id);
        return "redirect:/user/findByPage";
    }

//分页
    @RequestMapping("findByPage")
    public String findByPage(@RequestParam(value="pageNow",required = false) Integer pageNow,
                             @RequestParam(value = "pageSize",required = false) Integer pageSize,
                             Model model){
           Map<String,Object> result = new HashMap<>();
           pageNow = pageNow==null?1:pageNow;
           pageSize = pageSize==null?4:pageSize;
        int start=0;
        if(pageNow==null){
            start=1;
        }else {
            start = Integer.valueOf(pageNow);
            if (start < 1) {
                start = 1;
            }
        }
           List<User> users = userService.findByPage(start,pageSize);
           String totals = userService.findTotals();
           result.put("start",start);
           result.put("users",users);
           result.put("total",totals);
           /*System.out.println(totals);*/
           model.addAttribute("start",start);
           model.addAttribute("users",users);
           model.addAttribute("total",totals);
           return "demo";
    }





   @RequestMapping("lists")
   public String lists(Model model,User user){
      log.debug("查询所有登录用户信息");
       List<User> userList = userService.lists();
       model.addAttribute("userList",userList);
       return "demo";
   }

    @RequestMapping("generateImageCode")
    public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
      String code = VerifyCodeUtils.generateVerifyCode(4);

      session.setAttribute("code",code);
      response.setContentType("image/png");
      ServletOutputStream os = response.getOutputStream();
      VerifyCodeUtils.outputImage(220,60,os,code);
    }
}
